<?php

class ProfilesController extends AppController {

    var $name = 'Profiles';
//    var $components = array('RequestHandler', 'Access');
    var $uses = array('ProfileField', 'UserProfile', 'UserCredit', 'ProfileFieldValue', 'SubjectRate', 'Subject', 'Memberplan', 'Memberplantext', 'User', 'Tag', 'Subject', 'FeaturedSubject');
    var $components = array('RequestHandler', 'Access');
    
    function beforeFilter() {
        parent::beforeFilter();
        // echo $this->Session->setFlash("Welcome user");
        $this->Auth->autoRedirect = false;
        $this->Auth->allow('edit_profile', 'check_email', 'register', 'check_login', 'ajax_register', 'reload_captcha', 'confirm', 'successful', 'profile', 'urt', 'fs_search', 'fs_save', 'fs_public');
        $this->Auth->loginRedirect = array('controller' => 'Homes', 'action' => 'index');
    }

    function profile_edit() {
        // Configure::write('debug', '0');
        /**/

        $text = $this->Memberplantext->find('all');
        $plan = $this->Memberplan->find('all');
        $this->set('plan', $plan);
        $this->set('text', $text);
        /**/
        /* query for fetch profile fields */
        $user_id = $_SESSION['Auth']['user']['User']['id'];

        $user_register = $this->ProfileFieldValue->find('first', array('conditions' => array('ProfileFieldValue.user_id' => $user_id)));
        if ($user_register) {
            $userprofile = $this->ProfileField->query("SELECT ProfileField . * , ProfileFieldValue . * FROM profile_fields AS ProfileField LEFT JOIN profile_field_values AS ProfileFieldValue ON ProfileField.id = ProfileFieldValue.profile_field_id AND ProfileField.status='1'AND ProfileFieldValue.user_id='$user_id' ORDER BY ProfileField.order ");
            $this->set('profilefield', $userprofile);
        } else {

            $profilefield = $this->ProfileField->query("SELECT * from profile_fields as ProfileField  where status='1' ORDER BY `order`");
            $this->set('profilefield', $profilefield);
        }
        /*         * ********************** Users credits and ranking  ************************** */

        $this->set('rank', $this->get_user_ranking($user_id));
//            $this->set('rank_user',$this->user_nametmp($user_id));
        $this->set('rank_user', $this->_save_user_info($user_id));
        $this->set('detail_profile', $this->_save_user_profile($user_id));
        $this->set('get_user_infor', $this->_get_user_infor($user_id));
        $this->set('get_subject', $this->_get_profile_field());
        $this->set('get_univer', $this->_get_universal($user_id));

        $this->set('points', $this->get_points($user_id));
        $ratedsubjects = $this->SubjectRate->find('count', array('conditions' => array('SubjectRate.user_id' => $user_id), 'fields' => 'DISTINCT SubjectRate.subject_id'));
        $this->set('subjects_rated', $ratedsubjects);
        $subject_added = $this->Subject->find('count', array('conditions' => array('Subject.user_id' => $user_id, 'Subject.status' => '1')));
        $this->set('subject_added', $subject_added);

        /*         * ******************************************* */
        /* profile field end */
        if (isset($_SESSION['Auth']['user']['User']['id'])) {
            $userdetails = $this->UserProfile->find('first', array('conditions' => array('user_id' => $user_id)));
            $this->set('profile', $userdetails);
        }


        if (!empty($this->data)) {
            //debug($this->data);die();
            if (!empty($this->data['User']['password'])) {
                $this->data['User']['password'] = $this->Auth->password($this->data['User']['password']);
                $this->User->id = $this->Auth->User('id');
                $this->User->save($this->data);
            }

//            debug($this->data['UserProfile']['screenname']);die();
            $dob = $this->data['UserProfile']['dob']['year'] . '-' . $this->data['UserProfile']['dob']['month'] . '-' . $this->data['UserProfile']['dob']['day'];

            $mysql = $this->UserProfile->query("update  user_profiles  set `screenname`='" . $this->data['UserProfile']['screenname'] . "',`dob`='$dob' where user_id='" . $_SESSION['Auth']['user']['User']['id'] . "'");
            $ext = array();
            $sql = mysql_query("select image from user_profiles where user_id='" . $_SESSION['Auth']['user']['User']['id'] . "'");
            $imagedata = mysql_fetch_array($sql);
            if (isset($_FILES['image'])) {
                @unlink(WWW_ROOT . 'img/uploads/profileimage/' . $imagedata['image']);
            }
            // delete prev image from profileimage folder
            //$ext = pathinfo($_FILES['image']['name']);
            //$filename =uniqid(null,true). '.'.$ext['extension'];
            if (isset($_FILES['image'])) {
                $ext = pathinfo($_FILES['image']['name']);
            }
            $upload = false;
            if (isset($ext['extension'])) {
                $filename = uniqid(null, true) . '.' . $ext['extension'];
                $upload = move_uploaded_file($_FILES['image']['tmp_name'], WWW_ROOT . 'img/uploads/profileimage/RTU' . $filename);
            }

            if ($upload) {

                $mysql = mysql_query("update  user_profiles  set image='RTU$filename'  where user_id='" . $_SESSION['Auth']['user']['User']['id'] . "'") or die(mysql_error());
            }
            $rowss = array();
            // echo "select * from profile_field_values where user_id='" . $_SESSION['Auth']['user']['User']['id'] . "'";
            $query = mysql_query("select * from profile_field_values where user_id='" . $_SESSION['Auth']['user']['User']['id'] . "'") or die(mysql_error());

            while ($rows = mysql_fetch_array($query)) {
                $rowss[] = $rows['profile_field_id'];
            }

            $num_row = mysql_num_rows($query);
            if ($num_row > 0) {

                foreach ($this->data['Profiles'] as $key => $profile) {

                    if (strstr($key, 'status')) {
                        $keys = substr($key, 6);
                        if (!in_array($keys, $rowss)) {
                            if (is_array($profile)) {
                                $profile = implode($profile, ',');
                            }
                            if ($profile == '0') {
                                $profile = '';
                            }

                            $insert = "insert into profile_field_values(`user_id`,`profile_field_id`,`value`) value('" . $_SESSION['Auth']['user']['User']['id'] . "','" . str_replace("status", "", $key) . "','$profile')";
                            mysql_query($insert) or die(mysql_errno());
                        } else if (strstr($key, 'status')) {

                            $update1 = "update profile_field_values set status='$profile' where user_id='" . $_SESSION['Auth']['user']['User']['id'] . "' AND profile_field_id='" . str_replace("status", "", $key) . "'";
                            mysql_query($update1) or die(mysql_error());
                        }
                    } else {
                        if (is_array($profile)) {
                            $profile = implode($profile, ',');
                        }
                        if ($profile == '0') {
                            $profile = '';
                        }
                        $update2 = "update profile_field_values set value='$profile' where user_id='" . $_SESSION['Auth']['user']['User']['id'] . "' AND profile_field_id='" . str_replace("status", "", $key) . "'";

                        mysql_query($update2) or die(mysql_errno());
                    }
                }
                //  exit;
            } else {
                foreach ($this->data['Profiles'] as $key => $profile) {
                    if (!strstr($key, 'status')) {
                        if (is_array($profile)) {
                            $profile = implode($profile, ',');
                        }

                        if ($profile == '0') {
                            $profile = '';
                        }
                        $insert = "insert into profile_field_values(`user_id`,`profile_field_id`,`value`) value('" . $_SESSION['Auth']['user']['User']['id'] . "','" . str_replace("status", "", $key) . "','$profile')";
                        mysql_query($insert) or die(mysql_errno());
                    } else {
                        if (is_array($profile)) {
                            $profile = implode($profile, ',');
                        }
                        $update3 = "update profile_field_values set status='$profile' where user_id='" . $_SESSION['Auth']['user']['User']['id'] . "' AND profile_field_id='" . str_replace("status", "", $key) . "'";
                        mysql_query($update3) or die(mysql_errno());
                    }
                }
            }
            $this->Session->setFlash("Your Profile is Updated.");
            $this->redirect(array('controller' => 'Profiles', 'action' => 'profile_edit'));
        }
    }

    function profile($screenname = null) {
        $this->set('title_for_layout', 'Rate The Universe - Profile');
        
        $uri = $_SERVER[ 'REQUEST_URI' ];
        $uri_arr = explode("/",$uri);
        if($uri_arr[count($uri_arr)-1] != "profile") 
            $this->redirect(array('controller' => 'profiles', 'action' => 'profile'));
        
        if (isset($_SESSION['Auth']['user']['User']['id']))
            $user_id = $_SESSION['Auth']['user']['User']['id'];
        else
            $this->redirect(array('controller' => 'homes', 'action' => 'index'));

        $this->set('rank', $this->UserCredit->get_user_ranking($user_id));
//      $this->set('rank_user',$this->user_nametmp($user_id));
        $this->set('rank_user', $this->_save_user_info($user_id));
        $this->set('detail_profile', $this->_save_user_profile($user_id));
        //get user information from `user_profiles`
        $this->set('get_user_infor', $this->_get_user_infor($user_id));
        $this->set('get_subject', $this->_get_profile_field());
        $this->set('get_univer', $this->_get_universal($user_id));
        $this->set('trans_user_info', $this->_trans_user_info($user_id));        

        $points = $this->UserCredit->get_points($user_id);
        $this->set('points', $points);

        $ratedsubjects = $this->SubjectRate->find('count', array('conditions' => array('SubjectRate.user_id' => $user_id), 'fields' => 'DISTINCT SubjectRate.subject_id'));
        $this->set('subjects_rated', $ratedsubjects);
        $subject_added = $this->Subject->find('count', array('conditions' => array('Subject.user_id' => $user_id, 'Subject.status' => '1')));
        $this->set('subject_added', $subject_added);

        $this->set('level', $this->UserCredit->get_level($points));

        $userdetail = $this->User->find('first', array('conditions' => array('user_id' => $user_id)));
        $this->set('userdetail', $userdetail);
        
        $feature_subjects = $this->_get_featured_subject($user_id);
        $this->set('feature_subjects', $feature_subjects);
        $fs_check_list = "";
        foreach($feature_subjects as $key => $val)
            $fs_check_list .= $val['subject_id']."|";
        $this->set('fs_check_list', $fs_check_list);

        $userprofile = $this->ProfileField->query("SELECT ProfileField . * , ProfileFieldValue . * FROM profile_fields AS ProfileField LEFT JOIN profile_field_values AS ProfileFieldValue ON ProfileField.id = ProfileFieldValue.profile_field_Id AND ProfileField.status='1' AND ProfileFieldValue.user_id='$user_id' AND ProfileFieldValue.status='1' ORDER BY ProfileField.order ");
        $this->set('userprofile', $userprofile);
        $this->set('all_tags', $this->_get_tags());

        //data to show for voting history
        $this->set('user_rates',$this->_get_voting_history());
        /*
          if(isset($this->params['slug'])){
          $screenname=$this->params['slug'];
          }
          $user=$this->UserProfile->find('first',array('conditions'=>array('screenname'=>$screenname)));

          if (isset($user['UserProfile']['user_id'])) {
          $user_id = $user['UserProfile']['user_id'];
          } else {
          $user_id = $_SESSION['Auth']['user']['User']['id'];

          }

          if($user['UserProfile']['user_id'] || $_GET['url']=='profiles/profile'){
          $user_register = $this->ProfileFieldValue->find('first', array('conditions' => array('ProfileFieldValue.user_id' => $user_id)));
          if ($user_register) {
          $userprofile = $this->ProfileField->query("SELECT ProfileField . * , ProfileFieldValue . * FROM profile_fields AS ProfileField LEFT JOIN profile_field_values AS ProfileFieldValue ON ProfileField.id = ProfileFieldValue.profile_field_Id AND ProfileField.status='1'AND ProfileFieldValue.user_id='$user_id' AND ProfileFieldValue.status='1' ORDER BY ProfileField.order ");
          $this->set('profilefield', $userprofile);
          } else {

          $profilefield = $this->ProfileField->query("SELECT * from profile_fields as ProfileField  where status='1' ORDER BY order DESC");
          $this->set('profilefield', $profilefield);
          }
          if (isset($user_id)) {

          $userdetails = $this->UserProfile->find('first', array('conditions' => array('UserProfile.user_id' => $user_id)));
          $this->set('userdetails', $userdetails);
          $this->set('rank', $this->get_user_ranking($user_id));
          $this->set('points',$this->get_points($user_id));
          $ratedsubjects=$this->SubjectRate->find('count',array('conditions'=>array('SubjectRate.user_id'=>$user_id),'fields'=>'DISTINCT SubjectRate.subject_id'));
          $this->set('subjects_rated',$ratedsubjects);
          $subject_added=$this->Subject->find('count',array('conditions'=>array('Subject.user_id'=>$user_id,'Subject.status'=>'1')));
          $this->set('subject_added',$subject_added);
          }
          }else{

          App::import('Controller', 'Subjects');
          $subject1 = new SubjectsController;
          $subject1->constructClasses(165);
          $subject1->subject();
          die();
          //$this->redirect(array('controller'=>'subjects','action'=>'subject'));
          } */
    }
    
    //ajax tag tree
    function f_server() {
        if(!$this->RequestHandler->isAjax())
            $this->redirect(array('controller' => 'profiles', 'action' => 'profile'));
        
        if (!isset($_SESSION['Auth']['user']['User']['id']))
            die();
        
        App::import('Vendor', 'config');
        $jstree = new json_tree();
        if (isset($_GET["reconstruct"])) {
            $jstree->_reconstruct();
            die();
        }
        if (isset($_GET["analyze"])) {
            echo $jstree->_analyze();
            die();
        }

        if ($_REQUEST["operation"] && strpos("_", $_REQUEST["operation"]) !== 0 && method_exists($jstree, $_REQUEST["operation"])) {
            header("HTTP/1.0 200 OK");
            header('Content-type: text/json; charset=utf-8');
            header("Expires: Mon, 26 Jul 1997 05:00:00 GMT");
            //echo '[{"attr":{"id":"node_2","rel":"drive"},"data":"C:","state":"closed"},{"attr":{"id":"node_6","rel":"drive"},"data":"D:","state":""}]';//$jstree->{$_REQUEST["operation"]}($_REQUEST);
//        echo method_exists($jstree, $_REQUEST["operation"]);
            echo $jstree->{$_REQUEST["operation"]}($_REQUEST);
            die();
        }
        header("HTTP/1.0 404 Not Found");
    }
    
    //ajax urt research tool    
    function urt(){
        if (!isset($_SESSION['Auth']['user']['User']['id']))
            die();
        
//        if($this->ResquestHandler->isAjax() && $this->request->is('post'))
        if($this->RequestHandler->isAjax())
        {
            $htags = $_POST['htags'];
            $htype = $_POST['htype'];
            $hgender = $_POST['hgender'];
            $hage = $_POST['$hage'];
            $hreligion = $_POST['hreligion'];
            $hrace = $_POST['hrace'];
            $hsexual = $_POST['hsexual'];
            
            $hcountry = $_POST['$hcountry'];
            $hstate = $_POST['$hstate'];
            $hcity = $_POST['$hcity'];
            $hoccupation = $_POST['$hoccupation'];
            $hpet = $_POST['$hpet'];
            $hparent = $_POST['$hparent'];

            $heducation = $_POST['$heducation'];
            $hincome = $_POST['$hincome'];
            
            $this->SubjectRate->recursive = -1;
            $this->UserProfile->recursive = -1;
            
            $this->User->unbindModel(array('hasMany' => array('SubjectRate', 'UserCredit', 'Subject')));
            //$this->User->unbindModel(array('hasOne' => array('UserProfile')));
//            $hage = "1|20|30";
//            $hgender = "1|2";
//            $hreligion = "1|2";
//            $hrace = "1|2";
//            $hsexual = "1|2";
//            $heducation = "1|2";
//            $hincome = "1|2";
//
//            $hcountry = "2";
//            $hstate = "2";
//            $hcity = "2";
//            $hoccupation = "2";
//            $hpet = "2";
//            $hparent = "2";
            
            if(!empty($hage)){
                $hage = explode("|", $hage);
                $conditions = array();
                $rexp = "";                
                foreach($hage as $age_group){
                    switch($age_group){
                        case 1:
                            for($i=date('Y'); date('Y')-$i>=0 && date('Y')-$i<20; $i--)
                                $rexp .= $i."|";
                            break;
                        case 20:
                            for($i=date('Y')-20; date('Y')-$i<29; $i--)
                                $rexp .= $i."|";
                            break;
                        case 30:
                            for($i=date('Y')-30; date('Y')-$i<39; $i--)
                                $rexp .= $i."|";
                            break;
                        case 40:
                            for($i=date('Y')-40; date('Y')-$i<49; $i--)
                                $rexp .= $i."|";
                            break;
                        case 50:
                            for($i=date('Y')-50; date('Y')-$i<59; $i--)
                                $rexp .= $i."|";
                            break;
                        case 60:
                            for($i=date('Y')-60; date('Y')-$i<100; $i--)
                                $rexp .= $i."|";
                            break;
                    }
                }
                if(strlen($rexp)>0)
                    $rexp = substr($rexp, 0, -1);
                $user= $this->User->find('all', array(
                    'fields'=>array('User.id','UserProfile.dob'),
                    'conditions' => array(
                        "year(UserProfile.dob) regexp ('$rexp')"
                        )
                    )
                );
            }
            else
            {
                 $user= $this->User->find('all', array(
                    'fields'=>array('User.id','UserProfile.dob')
                    )
                );
            }
            $user_ids = array();
            foreach ($user as $item) {
                $user_ids[] = $item['User']['id'];
            }            
            $user_ids = implode('|', $user_ids);
            
            if(!empty($hgender)){
                $by_gender= $this->ProfileFieldValue->find('all', array(
                'fields' => array('ProfileFieldValue.user_id'),
                'conditions' => array("ProfileFieldValue.profile_field_id" => 15, 
                    "ProfileFieldValue.value regexp ('$hgender')",
                    "ProfileFieldValue.user_id regexp ('$user_ids')",
                    ),
                'recursive' => -1,
                'group' => array('ProfileFieldValue.user_id'),
                ));
                $user_ids = array();
                foreach($by_gender as $item)
                    $user_ids[] = $item['ProfileFieldValue']['user_id'];
                $user_ids = implode('|', $user_ids);
            }
            
            if(!empty($hreligion)){
                $by_religion= $this->ProfileFieldValue->find('all', array(
                'fields' => array('ProfileFieldValue.user_id'),
                'conditions' => array("ProfileFieldValue.profile_field_id" => 19, 
                    "ProfileFieldValue.value regexp ('$hreligion')",
                    "ProfileFieldValue.user_id regexp ('$user_ids')",
                    ),
                'recursive' => -1,
                'group' => array('ProfileFieldValue.user_id'),
                ));
                $user_ids = array();
                foreach($by_religion as $item)
                    $user_ids[] = $item['ProfileFieldValue']['user_id'];
                $user_ids = implode('|', $user_ids);
            }
            
            if(!empty($hrace)){
                $by_race= $this->ProfileFieldValue->find('all', array(
                'fields' => array('ProfileFieldValue.user_id'),
                'conditions' => array("ProfileFieldValue.profile_field_id" => 21, 
                    "ProfileFieldValue.value regexp ('$hrace')",
                    "ProfileFieldValue.user_id regexp ('$user_ids')",
                    ),
                'recursive' => -1,
                'group' => array('ProfileFieldValue.user_id'),
                ));
                $user_ids = array();
                foreach($by_race as $item)
                    $user_ids[] = $item['ProfileFieldValue']['user_id'];
                $user_ids = implode('|', $user_ids);
            }
            
            if(!empty($hsexual)){
                $by_sexual= $this->ProfileFieldValue->find('all', array(
                'fields' => array('ProfileFieldValue.user_id'),
                'conditions' => array("ProfileFieldValue.profile_field_id" => 29, 
                    "ProfileFieldValue.value regexp ('$hsexual')",
                    "ProfileFieldValue.user_id regexp ('$user_ids')",
                    ),
                'recursive' => -1,
                'group' => array('ProfileFieldValue.user_id'),
                ));
                $user_ids = array();
                foreach($by_sexual as $item)
                    $user_ids[] = $item['ProfileFieldValue']['user_id'];
                $user_ids = implode('|', $user_ids);
            }
            
            if(!empty($heducation)){
                $by_education= $this->ProfileFieldValue->find('all', array(
                'fields' => array('ProfileFieldValue.user_id'),
                'conditions' => array("ProfileFieldValue.profile_field_id" => 26, 
                    "ProfileFieldValue.value regexp ('$heducation')",
                    "ProfileFieldValue.user_id regexp ('$user_ids')",
                    ),
                'recursive' => -1,
                'group' => array('ProfileFieldValue.user_id'),
                ));
                $user_ids = array();
                foreach($by_education as $item)
                    $user_ids[] = $item['ProfileFieldValue']['user_id'];
                $user_ids = implode('|', $user_ids);
            }
            
            if(!empty($hincome)){
                $by_income= $this->ProfileFieldValue->find('all', array(
                'fields' => array('ProfileFieldValue.user_id'),
                'conditions' => array("ProfileFieldValue.profile_field_id" => 27, 
                    "ProfileFieldValue.value regexp ('$hincome')",
                    "ProfileFieldValue.user_id regexp ('$user_ids')",
                    ),
                'recursive' => -1,
                'group' => array('ProfileFieldValue.user_id'),
                ));
                $user_ids = array();
                foreach($by_income as $item)
                    $user_ids[] = $item['ProfileFieldValue']['user_id'];
                $user_ids = implode('|', $user_ids);
            }
            
            if(!empty($hcountry)){
                $by_country= $this->ProfileFieldValue->find('all', array(
                'fields' => array('ProfileFieldValue.user_id'),
                'conditions' => array("ProfileFieldValue.profile_field_id" => 20, 
                    "ProfileFieldValue.value"=>$hcountry,
                    "ProfileFieldValue.user_id regexp ('$user_ids')",
                    ),
                'recursive' => -1,
                'group' => array('ProfileFieldValue.user_id'),
                ));
                $user_ids = array();
                foreach($by_country as $item)
                    $user_ids[] = $item['ProfileFieldValue']['user_id'];
                $user_ids = implode('|', $user_ids);
            }
            
            if(!empty($hstate)){
                $by_state = $this->ProfileFieldValue->find('all', array(
                'fields' => array('ProfileFieldValue.user_id'),
                'conditions' => array("ProfileFieldValue.profile_field_id" => 25, 
                    "ProfileFieldValue.value"=>$hstate,
                    "ProfileFieldValue.user_id regexp ('$user_ids')",
                    ),
                'recursive' => -1,
                'group' => array('ProfileFieldValue.user_id'),
                ));
                $user_ids = array();
                foreach($by_state as $item)
                    $user_ids[] = $item['ProfileFieldValue']['user_id'];
                $user_ids = implode('|', $user_ids);
            }
            
            if(!empty($hcity)){
                $by_city = $this->ProfileFieldValue->find('all', array(
                'fields' => array('ProfileFieldValue.user_id'),
                'conditions' => array("ProfileFieldValue.profile_field_id" => 30, 
                    "ProfileFieldValue.value"=>$hcity,
                    "ProfileFieldValue.user_id regexp ('$user_ids')",
                    ),
                'recursive' => -1,
                'group' => array('ProfileFieldValue.user_id'),
                ));
                $user_ids = array();
                foreach($by_city as $item)
                    $user_ids[] = $item['ProfileFieldValue']['user_id'];
                $user_ids = implode('|', $user_ids);
            }
            
            if(!empty($hoccupation)){
                $by_occupation = $this->ProfileFieldValue->find('all', array(
                'fields' => array('ProfileFieldValue.user_id'),
                'conditions' => array("ProfileFieldValue.profile_field_id" => 31, 
                    "ProfileFieldValue.value"=>$hoccupation,
                    "ProfileFieldValue.user_id regexp ('$user_ids')",
                    ),
                'recursive' => -1,
                'group' => array('ProfileFieldValue.user_id'),
                ));
                $user_ids = array();
                foreach($by_occupation as $item)
                    $user_ids[] = $item['ProfileFieldValue']['user_id'];
                $user_ids = implode('|', $user_ids);
            }
            
            if(!empty($hpet)){
                $by_pet = $this->ProfileFieldValue->find('all', array(
                'fields' => array('ProfileFieldValue.user_id'),
                'conditions' => array("ProfileFieldValue.profile_field_id" => 24, 
                    "ProfileFieldValue.value"=>$hpet,
                    "ProfileFieldValue.user_id regexp ('$user_ids')",
                    ),
                'recursive' => -1,
                'group' => array('ProfileFieldValue.user_id'),
                ));
                $user_ids = array();
                foreach($by_pet as $item)
                    $user_ids[] = $item['ProfileFieldValue']['user_id'];
                $user_ids = implode('|', $user_ids);
            }
            
            if(!empty($hparent)){
                $by_parent = $this->ProfileFieldValue->find('all', array(
                'fields' => array('ProfileFieldValue.user_id'),
                'conditions' => array("ProfileFieldValue.profile_field_id" => 23, 
                    "ProfileFieldValue.value"=>$hparent,
                    "ProfileFieldValue.user_id regexp ('$user_ids')",
                    ),
                'recursive' => -1,
                'group' => array('ProfileFieldValue.user_id'),
                ));
                $user_ids = array();
                foreach($by_parent as $item)
                    $user_ids[] = $item['ProfileFieldValue']['user_id'];
                $user_ids = implode('|', $user_ids);
            }            
                        
            //Tag process : retrieve the subject_id array
            $this->Subject->unbindModel(array('hasMany' => array('SubjectRate', 'Comment', 'Attribute', 'SubjectAdjectives', 'Subjectredirect')));
            $o_str_htags = $htags;//"&nbsp;Animals/Plants/Life Forms(no food or people)|&nbsp;Places/Landmarks/Outer Space|&nbsp;Entertainment";
            if(!empty($o_str_htags))
            {
                //remove the &nbsp; strings
                $o_str_htags = str_replace('&nbsp;',"",$o_str_htags);
                $o_arr_htags = explode('|', $o_str_htags);
                //get only 3 last tag names
                if(count($o_arr_htags)>3){
                    $tmp = array();
                    for($i=1;$i<=3;$i++)
                        $tmp[] = $o_arr_htags[count($o_arr_htags)-$i];
                    unset($o_arr_htags);
                    $o_arr_htags = array();
                    for($i=count($tmp)-1;$i>-1;$i--)
                        $o_arr_htags[] = $tmp[$i];
                }
                $id_arr_htags = array();
                //each tag name, get the tag row whose title is the same
                foreach($o_arr_htags as $o_htags_item){
                    $tmp = $this->Tag->find('all', 
                            array(
                                'conditions' => array(
                                    'title'=>$o_htags_item), 
                                'fields' => array('Tag.id'), 
                                'order' => 'Tag.id ASC'));
                    foreach($tmp as $tmp_item)
                        $id_arr_htags[] = $tmp_item['Tag']['id'];
                }
                $tag_ids = array();
                //get the children of 3 tag
                foreach($id_arr_htags as $item){
                    $tag_ids[] = $item;
                    $childs = $this->Tag->children($item, false, 'id', 'level ASC');
                    foreach ($childs as $values) {
                        $tmp_val = ",".$values['Tag']['id'].',';
//                        $tmp_val = '^'.$tmp_val.'$';
//                        $tag_ids[] = '^'.$tmp_val.'$'."|^$tmp_val,"."|,$tmp_val$"."|,$tmp_val,";
                        $tag_ids[] = $tmp_val;
                    }           
                }
                //convert tag_ids to string for regexp
                $str_tag_ids = implode('|', $tag_ids);
                if (empty($str_tag_ids)) {
                    $str_tag_ids = implode('|', $id_arr_htags);
                }
                $tagsubjects = $this->Subject->find('all', 
                        array(
                            'conditions' => array("Subject.tag_ids regexp ('$str_tag_ids')", 'Subject.status' => '1', 'Subject.image !=' => ''), 
                            'fields' => array('Subject.subject', 'Subject.id'), 
                            'order' => 'Subject.subject ASC'));
                
            }
            else{
                $tagsubjects = $this->Subject->find('all', 
                        array(
                            'conditions' => array('Subject.status' => '1', 'Subject.image !=' => ''), 
                            'fields' => array('Subject.subject', 'Subject.id'), 
                            'order' => 'Subject.subject ASC'));
            }
            $subjects_ids = array();
            foreach ($tagsubjects as $values) {
                $subjects_ids[] = $values['Subject']['id'];                        
            }
            $str_subject_id = implode(',',$subjects_ids);
            
            //user_id is INT, must use `in` for SQL query, not `regexp` (only for text)
            $user_ids = str_replace('|',",",$user_ids);
            
            $conditions = array("SubjectRate.user_id in ($user_ids)", "SubjectRate.subject_id in ($str_subject_id)");//use ,
//            $conditions = array("SubjectRate.user_id regexp ('$user_ids')", "SubjectRate.subject_id regexp ('$str_subject_id')");//use |
            
            $join_table = array(
                    array('table' => 'subject',
                        'alias' => 'Subject',
                        'type' => 'INNER',
                        'conditions' => array(
                            'SubjectRate.subject_id = Subject.id',
                        )
                    )
            );
            $rates = $this->SubjectRate->find('all', array(
                'fields' => array('SubjectRate.id','SubjectRate.subject_id','SubjectRate.rating','SubjectRate.user_id','Subject.subject'),
                'conditions' => $conditions,
                'joins' => $join_table,
                'recursive' => -1,
                'order' => 'SubjectRate.subject_id ASC, SubjectRate.rating DESC'
            ));
            $mresult = array();
            foreach($rates as $rate){
                if(!isset($mresult[$rate['SubjectRate']['subject_id']])){
                    $mresult[$rate['SubjectRate']['subject_id']] = array();
                    $mresult[$rate['SubjectRate']['subject_id']]['subject_id'] = $rate['SubjectRate']['subject_id'];
                    $mresult[$rate['SubjectRate']['subject_id']]['subject_name'] = htmlspecialchars($rate['Subject']['subject'], ENT_QUOTES);
                    $mresult[$rate['SubjectRate']['subject_id']]['max_rate'] = $rate['SubjectRate']['rating'];
                    $mresult[$rate['SubjectRate']['subject_id']]['min_rate'] = $rate['SubjectRate']['rating'];
                    $mresult[$rate['SubjectRate']['subject_id']]['arr_rate'] = array();
                    $mresult[$rate['SubjectRate']['subject_id']]['arr_rate'][] = $rate['SubjectRate']['rating'];
                    $mresult[$rate['SubjectRate']['subject_id']]['avg_rate'] = $rate['SubjectRate']['rating'];
                }
                else{
                    if($mresult[$rate['SubjectRate']['subject_id']]['max_rate']<$rate['SubjectRate']['rating'])
                        $mresult[$rate['SubjectRate']['subject_id']]['max_rate'] = $rate['SubjectRate']['rating'];
                    if($mresult[$rate['SubjectRate']['subject_id']]['min_rate']>$rate['SubjectRate']['rating'])
                        $mresult[$rate['SubjectRate']['subject_id']]['min_rate'] = $rate['SubjectRate']['rating'];
                    $mresult[$rate['SubjectRate']['subject_id']]['arr_rate'][] = $rate['SubjectRate']['rating'];
                    $mresult[$rate['SubjectRate']['subject_id']]['avg_rate'] = array_sum($mresult[$rate['SubjectRate']['subject_id']]['arr_rate'])/count($mresult[$rate['SubjectRate']['subject_id']]['arr_rate']);
                }
            }
            foreach($mresult as $key => $val){
                $mresult[$key]['frequently'] = 0;
                $mresult[$key]['avg_rate'] = floor(array_sum($mresult[$key]['arr_rate'])/count($mresult[$key]['arr_rate']));
                
                $arr_fre = array();
                foreach($mresult[$key]['arr_rate'] as $k => $v){
                    if(array_key_exists($v, $arr_fre)){
                        $arr_fre["$v"] = $arr_fre["$v"] + 1;
                    }else{
                        $arr_fre["$v"] = 1;
                    }
                }
                $max_count = NULL;
                $max_index = NULL;
                foreach($arr_fre as $k => $v){
                    if(!isset($max_count)&&!isset($max_index)){
                        $max_count = $v;
                        $max_index = $k;
                    }else
                    if($max_count<$v){
                        $max_count = $v;
                        $max_index = $k;
                    }                        
                }
                $mresult[$key]['frequently'] = $max_index;
            }
            $result = array();
            foreach($mresult as $key => $val){
                $result[]=$val;
            }
            
//            var_dump($user_ids);
//            var_dump($str_subject_id);
//            var_dump($rates);
//            echo "-----------------------------";
//            var_dump($mresult);
//            echo "-----------------------------";
//            var_dump($result);
            echo(json_encode($result));
            die();
            
            
//              $join_table = array(
//                    array('table' => 'subject_rates',
//                        'alias' => 'SubjectRate',
//                        'type' => 'INNER',
//                        'conditions' => array(
//                            'SubjectRate.user_id = UserProfile.user_id',
//                        )
//                    ),
//                    array('table' => 'profile_field_values',
//                        'alias' => 'ProfileFieldValue',
//                        'type' => 'INNER',
//                        'conditions' => array(
//                            'ProfileFieldValue.user_id = UserProfile.user_id',
//                        )
//                    )
//                );
//                    
//            $conditions = array('UserProfile.user_id' => 1, "SubjectRate.subject_id regexp ('389|302|280')");
//            $user_profile= $this->UserProfile->find('all', array(
//            'fields' => array('SubjectRate.subject_id', 'count(*) as hasnum'),
//            'joins' => $join_table,
//            'conditions' => $conditions,
//            'recursive' => -1,
//            'group' => array('SubjectRate.subject_id'),
//            'order' => 'hasnum DESC'
//                ));
//            
//            var_dump($user_profile);
        }
        $this->redirect(array('controller' => 'profiles', 'action' => 'profile'));
    }    
    
    //ajax featured subject
    function fs_search(){
        if (isset($_SESSION['Auth']['user']['User']['id']))
            $user_id = $_SESSION['Auth']['user']['User']['id'];
        else
            die();        
        
        if($this->RequestHandler->isAjax()){
            $aj_tag1 = $_POST['aj_tag1'];
            $aj_tag2 = $_POST['aj_tag1'];
            $aj_tag3 = $_POST['aj_tag3'];
            $aj_txt = $_POST['aj_txt'];
            
//            $aj_tag1 = 'Animals/Plants/Life Forms(no food or people)';
//            $aj_tag2 = 'Entertainment';
//            $aj_tag3 = 'Places/Landmarks/Outer Space';
//            $aj_txt = '';
            
//            $aj_tag1 = '0';
//            $aj_tag2 = '0';
//            $aj_tag3 = '0';
//            $aj_txt = '';
            
//            $this->SubjectRate->recursive = -1;
//            $this->UserProfile->recursive = -1;            
//            $this->User->unbindModel(array('hasMany' => array('SubjectRate', 'UserCredit', 'Subject')));
            
            //Tag process : retrieve the subject_id array
            $this->Subject->unbindModel(array('hasMany' => array('SubjectRate', 'Comment', 'Attribute', 'SubjectAdjectives', 'Subjectredirect')));
            $o_str_htags = $htags;//"&nbsp;Animals/Plants/Life Forms(no food or people)|&nbsp;Places/Landmarks/Outer Space|&nbsp;Entertainment";
//            if(!empty($o_str_htags))
            if(!empty($aj_tag1)||!empty($aj_tag2)||!empty($aj_tag3)||!empty($aj_txt))
            {
                $o_arr_htags = array();
                if(!empty($aj_tag1))
                    $o_arr_htags[] = $aj_tag1;
                if(!empty($aj_tag2))
                    $o_arr_htags[] = $aj_tag2;
                if(!empty($aj_tag3))
                    $o_arr_htags[] = $aj_tag3;

                $id_arr_htags = array();
                //each tag name, get the tag row whose title is the same
                foreach($o_arr_htags as $o_htags_item){
                    $tmp = $this->Tag->find('all', 
                            array(
                                'conditions' => array(
                                    'title'=>$o_htags_item), 
                                'fields' => array('Tag.id'), 
                                'order' => 'Tag.id ASC'));
                    foreach($tmp as $tmp_item)
                        $id_arr_htags[] = $tmp_item['Tag']['id'];
                }
                $tag_ids = array();
                //get the children of 3 tag
                foreach($id_arr_htags as $item){
                    $tag_ids[] = $item;
                    $childs = $this->Tag->children($item, false, 'id', 'level ASC');
                    foreach ($childs as $values) {
                        $tmp_val = $values['Tag']['id'];
                        $tmp_val = '^'.$tmp_val.'$';
//                        $tag_ids[] = '^'.$tmp_val.'$'."|^$tmp_val,"."|,$tmp_val$"."|,$tmp_val,";
                    }           
                }
                //convert tag_ids to string for regexp
                $str_tag_ids = implode('|', $tag_ids);
                if (empty($str_tag_ids)) {
                    $str_tag_ids = implode('|', $id_arr_htags);
                }
                
                $condition = array("Subject.tag_ids regexp ('$str_tag_ids')", 'Subject.status' => '1', 'Subject.image !=' => '');
                if(isset($aj_txt))
                    $condition['Subject.subject LIKE'] = "%$aj_txt%";
                
                $tagsubjects = $this->Subject->find('all', 
                        array(
//                            'conditions' => array("Subject.tag_ids regexp ('$str_tag_ids')", 'Subject.status' => '1', 'Subject.image !=' => ''), 
                            'conditions' => $condition,
                            'fields' => array('Subject.subject', 'Subject.id'), 
                            'order' => 'Subject.subject ASC'));
            }
            else{
                $tagsubjects = $this->Subject->find('all', 
                        array(
                            'conditions' => array('Subject.status' => '1', 'Subject.image !=' => ''), 
                            'fields' => array('Subject.subject', 'Subject.id'), 
                            'order' => 'Subject.subject ASC'));
            }
            
            $subjects_ids = array();
            foreach ($tagsubjects as $values) {
                $subjects_ids[] = $values['Subject']['id'];                        
            }
            $str_subject_id = implode(',',$subjects_ids);
            
            $join_table = array(
                    array('table' => 'subject_rates',
                        'alias' => 'SubjectRate',
                        //'type' => 'LEFT',//get subjects that not exist the user's subject rate for them
                        'type' => 'INNER',//get subjects that must exist the user's subject rate for them
                        'conditions' => array(
                            'SubjectRate.subject_id = Subject.id','SubjectRate.user_id' => $user_id
                        )
                    )
             );
            ////// NEED SubjectRate.user_id
            $conditions = array("Subject.id in ($str_subject_id)", "Subject.image !="=>"");
//            $conditions = array("Subject.id in ($str_subject_id)");
            $rates= $this->Subject->find('all', array(
                'fields' => array('Subject.id', 'Subject.subject', 'Subject.image', 'SubjectRate.rating', 'SubjectRate.user_id'),
                'joins' => $join_table,
                'conditions' => $conditions,
                'recursive' => -1,
                'order' => 'Subject.subject ASC, SubjectRate.rating DESC'
            ));
            
            $mresult = array();
            foreach($rates as $rate){
                if(!isset($mresult[$rate['Subject']['id']])){
                    $mresult[$rate['Subject']['id']] = array();
                    $mresult[$rate['Subject']['id']]['subject_id'] = $rate['Subject']['id'];
                    $mresult[$rate['Subject']['id']]['subject_name'] = htmlspecialchars($rate['Subject']['subject'], ENT_QUOTES);
                    $mresult[$rate['Subject']['id']]['image'] = $rate['Subject']['image'];
                    $mresult[$rate['Subject']['id']]['max_rate'] = $rate['SubjectRate']['rating'];
                    $mresult[$rate['Subject']['id']]['min_rate'] = $rate['SubjectRate']['rating'];
                    $mresult[$rate['Subject']['id']]['arr_rate'] = array();
                    $mresult[$rate['Subject']['id']]['arr_rate'][] = $rate['SubjectRate']['rating'];
                    $mresult[$rate['Subject']['id']]['avg_rate'] = $rate['SubjectRate']['rating'];
                }
                else{
                    if($mresult[$rate['Subject']['id']]['max_rate']<$rate['SubjectRate']['rating'])
                        $mresult[$rate['Subject']['id']]['max_rate'] = $rate['SubjectRate']['rating'];
                    if($mresult[$rate['Subject']['id']]['min_rate']>$rate['SubjectRate']['rating'])
                        $mresult[$rate['Subject']['id']]['min_rate'] = $rate['SubjectRate']['rating'];
                    $mresult[$rate['Subject']['id']]['arr_rate'][] = $rate['SubjectRate']['rating'];
                    $mresult[$rate['Subject']['id']]['avg_rate'] = array_sum($mresult[$rate['Subject']['id']]['arr_rate'])/count($mresult[$rate['Subject']['id']]['arr_rate']);
                }
            }
            foreach($mresult as $key => $val){
                $mresult[$key]['frequently'] = 0;
                $mresult[$key]['avg_rate'] = floor(array_sum($mresult[$key]['arr_rate'])/count($mresult[$key]['arr_rate']));
                
                $arr_fre = array();
                foreach($mresult[$key]['arr_rate'] as $k => $v){
                    if(array_key_exists($v, $arr_fre)){
                        $arr_fre["$v"] = $arr_fre["$v"] + 1;
                    }else{
                        $arr_fre["$v"] = 1;
                    }
                }
                $max_count = NULL;
                $max_index = NULL;
                foreach($arr_fre as $k => $v){
                    if(!isset($max_count)&&!isset($max_index)){
                        $max_count = $v;
                        $max_index = $k;
                    }else
                    if($max_count<$v){
                        $max_count = $v;
                        $max_index = $k;
                    }                        
                }
                $mresult[$key]['frequently'] = $max_index;
            }
            $result = array();
            foreach($mresult as $key => $val){
                $result[]=$val;
            }
            echo(json_encode($result));die();         
        }else{
            $this->redirect(array('controller' => 'profiles', 'action' => 'profile'));
        }
    }
    
    //ajax for saving featured subject
    //ref: http://book.cakephp.org/1.3/en/view/1031/Saving-Your-Data
    function fs_save(){
        if (isset($_SESSION['Auth']['user']['User']['id']))
            $user_id = $_SESSION['Auth']['user']['User']['id'];
        else
            die();
        
        if($this->RequestHandler->isAjax()){
            $aj_feature_sub = $_POST['aj_feature_sub'];
            $feature_sub_id_list = explode("|",$aj_feature_sub);
            //filter the repeated id
            $arr_tmp = array();
            foreach($feature_sub_id_list as $item)
                if(!isset($arr_tmp["$item"]))
                    $arr_tmp["$item"] = true;
            unset($feature_sub_id_list);
            $feature_sub_id_list = array();
            foreach($arr_tmp as $key => $val)
                $feature_sub_id_list[] = $key;
            if(empty($feature_sub_id_list[count($feature_sub_id_list)-1]))
                unset($feature_sub_id_list[count($feature_sub_id_list)-1]);              
                
            $this->FeaturedSubject->unbindModel(array('hasOne' => array('Subject','SubjectRate')));
            $conditions = array('FeaturedSubject.user_id' => $user_id);
            $feature_subjects = $this->FeaturedSubject->find('all', array(
                'fields' => array('FeaturedSubject.id', 'FeaturedSubject.subject_id', 'FeaturedSubject.order'),
                'conditions' => $conditions,
                'recursive' => 0,
                'order' => 'FeaturedSubject.id ASC'
                 ));
            //if there's not enough 20 records
            if(count($feature_subjects)<20){
                $default_data = array();
                $default_data['FeaturedSubject'] = array();
                for($i=0;$i<20-count($feature_subjects);$i++)
                    $default_data['FeaturedSubject'][] = array('user_id'=>$user_id, 'subject_id'=>0, 'order'=>0);
                $result_save = $this->FeaturedSubject->saveAll($default_data['FeaturedSubject']);                
            }
            //query again
            $feature_subjects = $this->FeaturedSubject->find('all', array(
                'fields' => array('FeaturedSubject.id', 'FeaturedSubject.subject_id', 'FeaturedSubject.order'),
                'conditions' => $conditions,
                'recursive' => 0,
                'order' => 'FeaturedSubject.id ASC'
                 ));            
            //reset all order to 0
            $save_back_fs = array();
            foreach($feature_subjects as $item){
                $tmp = $item['FeaturedSubject'];
                $tmp['order'] = 0;
                $save_back_fs[] = $tmp;
            }
            for($i=0;$i<count($feature_sub_id_list);$i++){
                $save_back_fs[$i]['order'] = $i+1;
                $save_back_fs[$i]['subject_id'] = $feature_sub_id_list[$i];
            }                
            $result_save = $this->FeaturedSubject->saveAll($save_back_fs);
            $str_return_json = array();
            $str_return_json['result'] = false;
            if($result_save){
                $this->Session->setFlash("New featured_subjects records are saved!");
                $str_return_json['result'] = true;
            }
            $str_return_json['fs_check_list'] = implode('|',$feature_sub_id_list);
            if($str_return_json['fs_check_list'] != '')
                $str_return_json['fs_check_list'] .= '|';
            echo(json_encode($str_return_json));die();
        }else{
            $this->redirect(array('controller' => 'profiles', 'action' => 'profile'));
        }
    }
    
    //ajax for save public featured subject
    function fs_public(){
        if (isset($_SESSION['Auth']['user']['User']['id']))
            $user_id = $_SESSION['Auth']['user']['User']['id'];
        else
            die();
        
        if($this->RequestHandler->isAjax()){
            $fs_public = $_POST['fs_public'];
            $this->User->unbindModel(array('hasMany' => array('UserCredit','Subject','SubjectRate'), 'hasOne' => array('UserProfile')));
            $user = $this->User->find('first', array('conditions' => array('id' => $user_id)));
            $user['User']['public_fs'] = $fs_public;
//            $user['User']['status'] = $fs_public;
            $result = $this->User->save($user['User']);
            //OR $result = $this->User->save($user);
//            var_dump($user);
            die();//$result is array
        }else{
            $this->redirect(array('controller' => 'profiles', 'action' => 'profile'));
        }
    }
    
    function _get_featured_subject($user_id){        
       $join_table = array(
            array('table' => 'subject_rates',
                'alias' => 'SubjectRate',
                'type' => 'INNER',//get featured_subjects that must exist the user's subject rate for them
                'conditions' => array(
                    'SubjectRate.subject_id = FeaturedSubject.subject_id','SubjectRate.user_id = FeaturedSubject.user_id'
                )
            ),
            array('table' => 'subject',
                'alias' => 'Subject',
                'type' => 'INNER',//get featured_subjects that must exist the user's subject for them
                'conditions' => array(
                    'Subject.id = FeaturedSubject.subject_id'
                )
            )
        );
        $conditions = array('FeaturedSubject.user_id' => $user_id, 'FeaturedSubject.order !=' => 0);
        $db_feature_subjects = $this->FeaturedSubject->find('all', array(
            'fields' => array('Subject.subject', 'Subject.image', 'FeaturedSubject.user_id', 'FeaturedSubject.subject_id', 'SubjectRate.rating'),
            'joins' => $join_table,
            'recursive' => -1,
            'order' => 'Subject.subject ASC, SubjectRate.rating DESC',
            'conditions' => $conditions
         ));
        $mresult = array();
        foreach($db_feature_subjects as $db_feature_subject){
            if(!isset($mresult["".$db_feature_subject['FeaturedSubject']['subject_id']])){
                $mresult["".$db_feature_subject['FeaturedSubject']['subject_id']] = array();
                $mresult["".$db_feature_subject['FeaturedSubject']['subject_id']]['subject_id'] = $db_feature_subject['FeaturedSubject']['subject_id'];
                $mresult["".$db_feature_subject['FeaturedSubject']['subject_id']]['subject_name'] = htmlspecialchars($db_feature_subject['Subject']['subject'], ENT_QUOTES);
                $mresult["".$db_feature_subject['FeaturedSubject']['subject_id']]['image'] = $db_feature_subject['Subject']['image'];
                $mresult["".$db_feature_subject['FeaturedSubject']['subject_id']]['user_id'] = $db_feature_subject['FeaturedSubject']['user_id'];
                $mresult["".$db_feature_subject['FeaturedSubject']['subject_id']]['max_rate'] = $db_feature_subject['SubjectRate']['rating'];
                $mresult["".$db_feature_subject['FeaturedSubject']['subject_id']]['min_rate'] = $db_feature_subject['SubjectRate']['rating'];
                $mresult["".$db_feature_subject['FeaturedSubject']['subject_id']]['frequently'] = $db_feature_subject['SubjectRate']['rating'];
                $mresult["".$db_feature_subject['FeaturedSubject']['subject_id']]['avg_rate'] = $db_feature_subject['SubjectRate']['rating'];
                $mresult["".$db_feature_subject['FeaturedSubject']['subject_id']]['arr_rate'] = array();
                $mresult["".$db_feature_subject['FeaturedSubject']['subject_id']]['arr_rate'][] = $db_feature_subject['SubjectRate']['rating'];
            }else{
                if($mresult["".$db_feature_subject['FeaturedSubject']['subject_id']]['max_rate']<$db_feature_subject['SubjectRate']['rating'])
                        $mresult["".$db_feature_subject['FeaturedSubject']['subject_id']]['max_rate'] = $db_feature_subject['SubjectRate']['rating'];
                if($mresult["".$db_feature_subject['FeaturedSubject']['subject_id']]['min_rate']>$db_feature_subject['SubjectRate']['rating'])
                        $mresult["".$db_feature_subject['FeaturedSubject']['subject_id']]['min_rate'] = $db_feature_subject['SubjectRate']['rating'];
                $mresult["".$db_feature_subject['FeaturedSubject']['subject_id']]['arr_rate'][] = $db_feature_subject['SubjectRate']['rating'];
                $mresult["".$db_feature_subject['FeaturedSubject']['subject_id']]['avg_rate'] = array_sum($mresult["".$db_feature_subject['FeaturedSubject']['subject_id']]['avg_rate'])/count($mresult["".$db_feature_subject['FeaturedSubject']['subject_id']]['avg_rate']);
            }                
        }
        foreach($mresult as $key => $val){
            $mresult[$key]['frequently'] = 0;
            $mresult[$key]['avg_rate'] = floor(array_sum($mresult[$key]['arr_rate'])/count($mresult[$key]['arr_rate']));

            $arr_fre = array();
            foreach($mresult[$key]['arr_rate'] as $k => $v){
                if(array_key_exists($v, $arr_fre)){
                    $arr_fre["$v"] = $arr_fre["$v"] + 1;
                }else{
                    $arr_fre["$v"] = 1;
                }
            }
            $max_count = NULL;
            $max_index = NULL;
            foreach($arr_fre as $k => $v){
                if(!isset($max_count)&&!isset($max_index)){
                    $max_count = $v;
                    $max_index = $k;
                }else
                if($max_count<$v){
                    $max_count = $v;
                    $max_index = $k;
                }                        
            }
            $mresult[$key]['frequently'] = $max_index;
        }
        $result = array();
        foreach($mresult as $key => $val){
            $result[]=$val;
        }
        return $result;
    }
    
    function _user_nametmp($user_id) {
        $rank_user = array();
        $rank_user['usernametmp'] = $user_id;
        return $rank_user;
    }

    function get_user_ranking($user_id) {

        $get_credits = mysql_query("SELECT SUM(`credit`) as points ,`user_id`FROM `user_credits` GROUP BY `user_id` ORDER BY points DESC");
        $users = array();
        $rank = array();
        $i = '0';
        while ($row = mysql_fetch_assoc($get_credits)) {
            $users[$i]['id'] = $row['user_id'];
            $users[$i]['points'] = $row['points'];
            $i++;
        }
        //debug($users);

        $uids = Set::classicExtract($users, '{n}.id');
        $position = array_search($user_id, $uids);
        if ($position) {
            $rank['rank'] = $position + 1;
            $rank['points'] = $users[$position]['points'];
        } else {
            $rank['rank'] = count($uids) + 1;
        }
        return $rank;
    }

    function change_image() {
        if ($this->RequestHandler->isAjax()) {
            $this->autoRender = false;
            $user_id = $_SESSION['Auth']['user']['User']['id'];
        }
    }

    function check_image_extension($ext) {
        $response = false;
        $allowedext = array('jpg', 'JPG', 'jpeg', 'JPEG', 'pjpeg', 'png', 'PNG');
        foreach ($allowedext as $extension) {
            if ($extension == $ext) {
                $response = true;
                break;
            }
        }
        return $response;
    }

    function check_screenname() {
        if ($this->RequestHandler->isAjax()) {
            $this->autoRender = false;
            if (isset($_POST['name'])) {

                echo $check = $this->UserProfile->find('count', array('conditions' => array('UserProfile.screenname' => $_POST['name'], 'UserProfile.user_id !=' => $_SESSION['Auth']['user']['User']['id'])));
            }
        }
    }

    function payment() {
        $this->autoRender = false;
        if (isset($_REQUEST['txn_id'])) {

            $sql = mysql_query("update user_profiles  set account_type='" . $_REQUEST['item_name'] . "',duration='" . $_REQUEST['item_number'] . "',transaction_id='" . $_REQUEST['txn_id'] . "',paid_account_created=NOW() where user_id='" . $_SESSION['Auth']['user']['User']['id'] . "'");
            echo "Thanx for Payment\n Your Account Update sortly.";
            exit;
        }
    }

    function _save_user_info($user_id) {
        if ($_POST['firstname'] != "") {
            
            $oldpassword = $_POST['oldpassword'];
            $lastname = $_POST['lastname'];
            $username = $_POST['username'];
            $email = $_POST['email'];
            $confirmpassword = $_POST['confirmpassword'];
            $newpassword = $_POST['newpassword'];
//            $oldpassword = $this->Auth->password($oldpassword);
            //check new user name
            $check_un_sql = "select * from user where id!='" . $user_id . "' and username='" . $username . "'";
            $get_check_un = mysql_query($check_un_sql);            
            $no_rows_check_un = mysql_num_rows($get_check_un);         
            if($no_rows_check_un>0) {
                $result->code = 1;
                $result->attempt_username = $username;   
                return $result;//duplicated username
            }
            
            $select = "select * from user where id='" . $user_id . "' and password='" . $oldpassword . "'";
            $get_credits = mysql_query($select);            
            $no_rows = mysql_num_rows($get_credits);
            if ($no_rows == 1) {
                if ($newpassword == $confirmpassword) {
                    $update = "update user set email='" . $email . "' ,username='" . $username . "' where id='" . $user_id . "'";
                    mysql_query($update);
                    
                    if($newpassword !=  $oldpassword){
                        $update = "update user set password='" . $this->Auth->password($newpassword) . "' where id='" . $user_id . "'";
                        mysql_query($update);
                    }

                    $update_infor = "update user_profiles set screenname='" . $_POST['firstname'] . "' where user_id='" . $user_id . "'";
                    mysql_query($update_infor);
                }

                $select_profiles = "select * from profile_field_values where user_id='" . $user_id . "' and profile_field_id='13'";
                $get_credits = mysql_query($select_profiles);
                $no_rows = mysql_num_rows($get_credits);
                if ($no_rows == 1) {
                    $update = "update profile_field_values set value='" . $_POST['firstname'] . "' where profile_field_id='13'";
                    mysql_query($update);
                } else {
                    $insert = "insert into profile_field_values(`user_id`,`profile_field_id`,`value`) value('" . $user_id . "','13','" . $_POST['firstname'] . "')";
                    mysql_query($insert);
                }
                $select_profiles = "select * from profile_field_values where user_id='" . $user_id . "' and profile_field_id='14'";
                $get_credits = mysql_query($select_profiles);
                $no_rows = mysql_num_rows($get_credits);
                if ($no_rows == 1) {
                    $update = "update profile_field_values set value='" . $lastname . "' where profile_field_id='14'";
                    mysql_query($update);
                } else {
                    $insert = "insert into profile_field_values(`user_id`,`profile_field_id`,`value`) value('" . $user_id . "','14','" . $lastname . "')";
                    mysql_query($insert);
                }               
                
                $result->code = 0;
                return $result;
            }
        }
    }

    function _save_user_profile($user_id) {
        $About = $_POST['About'];
        $hid_about = $_POST['hid_about'];
        $sts_about = 1;
        if(isset($hid_about)) $sts_about = 0;
        if ($About != "") {
            $select_profiles = "select * from profile_field_values where user_id='" . $user_id . "' and profile_field_id='33'";
            $get_credits = mysql_query($select_profiles);
            $no_rows = mysql_num_rows($get_credits);
            if ($no_rows == 1) {
                $update = "update profile_field_values set value='" . $About . "', status=$sts_about where profile_field_id='33' and user_id='" . $user_id . "' ";
                mysql_query($update);
            } else {
                $insert = "insert into profile_field_values(`user_id`,`profile_field_id`,`value`,`status`) value('" . $user_id . "','33','" . $About . "', $sts_about)";
                mysql_query($insert);
                $users['firstname'] = $insert;
            }
        }
        
        $Gender = $_POST['Gender'];
        $hid_gender = $_POST['hid_gender'];
        $sts_gender = 1;
        if(isset($hid_gender)) $sts_gender = 0;
        if ($Gender != "") {
            $select_profiles = "select * from profile_field_values where user_id='" . $user_id . "' and profile_field_id='15'";
            $get_credits = mysql_query($select_profiles);
            $no_rows = mysql_num_rows($get_credits);
            if ($no_rows == 1) {
                $update = "update profile_field_values set value='" . $Gender . "', status=$sts_gender where profile_field_id='15' and user_id='" . $user_id . "' ";
                mysql_query($update);
            } else {
                $insert = "insert into profile_field_values(`user_id`,`profile_field_id`,`value`,`status`) value('" . $user_id . "','15','" . $Gender . "', $sts_gender)";
                mysql_query($insert);
            }
        }

        $Country = $_POST['Country'];
        $hid_country = $_POST['hid_country'];
        $sts_country = 1;
        if(isset($hid_country)) $sts_country = 0;
        if ($Country != "") {
            $select_profiles = "select * from profile_field_values where user_id='" . $user_id . "' and profile_field_id='20'";
            $get_credits = mysql_query($select_profiles);
            $no_rows = mysql_num_rows($get_credits);
            if ($no_rows == 1) {
                $update = "update profile_field_values set value='" . $Country . "', status=$sts_country where profile_field_id='20' and user_id='" . $user_id . "' ";
                mysql_query($update);
            } else {
                $insert = "insert into profile_field_values(`user_id`,`profile_field_id`,`value`,`status`) value('" . $user_id . "','20','" . $Country . "', $sts_country)";
                mysql_query($insert);
            }
        }
        
        $State = $_POST['State'];
        $hid_state = $_POST['hid_state'];
        $sts_state = 1;
        if(isset($hid_state)) $sts_state = 0;
        if ($State != "") {
            $select_profiles = "select * from profile_field_values where user_id='" . $user_id . "' and profile_field_id='25'";
            $get_credits = mysql_query($select_profiles);
            $no_rows = mysql_num_rows($get_credits);
            if ($no_rows == 1) {
                $update = "update profile_field_values set value='" . $State . "', status=$sts_state where profile_field_id='25' and user_id='" . $user_id . "' ";
                mysql_query($update);
            } else {
                $insert = "insert into profile_field_values(`user_id`,`profile_field_id`,`value`,`status`) value('" . $user_id . "','25','" . $State . "', $sts_state)";
                mysql_query($insert);
            }
        }

        $City = $_POST['City'];
        $hid_city = $_POST['hid_city'];
        $sts_city = 1;
        if(isset($hid_city)) $sts_city = 0;
        if ($City != "") {
            $select_profiles = "select * from profile_field_values where user_id='" . $user_id . "' and profile_field_id='30'";
            $get_credits = mysql_query($select_profiles);
            $no_rows = mysql_num_rows($get_credits);
            if ($no_rows == 1) {
                $update = "update profile_field_values set value='" . $City . "', status=$sts_city where profile_field_id='30' and user_id='" . $user_id . "' ";
                mysql_query($update);
            } else {
                $insert = "insert into profile_field_values(`user_id`,`profile_field_id`,`value`,`status`) value('" . $user_id . "','30','" . $City . "', $sts_city)";
                mysql_query($insert);
            }
        }

        $Race = $_POST['Race'];
        $hid_race = $_POST['hid_race'];
        $sts_race = 1;
        if(isset($hid_race)) $sts_race = 0;
        if ($Race != "") {
            $select_profiles = "select * from profile_field_values where user_id='" . $user_id . "' and profile_field_id='21'";
            $get_credits = mysql_query($select_profiles);
            $no_rows = mysql_num_rows($get_credits);
            if ($no_rows == 1) {
                $update = "update profile_field_values set value='" . $Race . "', status=$sts_race where profile_field_id='21' and user_id='" . $user_id . "' ";
                mysql_query($update);
            } else {
                $insert = "insert into profile_field_values(`user_id`,`profile_field_id`,`value`,`status`) value('" . $user_id . "','21','" . $Race . "', $sts_race)";
                mysql_query($insert);
            }
        }
        
        $Religion = $_POST['Religion'];
        $hid_religion = $_POST['hid_religion'];
        $sts_religion = 1;
        if(isset($hid_religion)) $sts_religion = 0;
        if ($Religion != "") {
            $select_profiles = "select * from profile_field_values where user_id='" . $user_id . "' and profile_field_id='19'";
            $get_credits = mysql_query($select_profiles);
            $no_rows = mysql_num_rows($get_credits);
            if ($no_rows == 1) {
                $update = "update profile_field_values set value='" . $Religion . "', status=$sts_religion where profile_field_id='19' and user_id='" . $user_id . "' ";
                mysql_query($update);
            } else {
                $insert = "insert into profile_field_values(`user_id`,`profile_field_id`,`value`,`status`) value('" . $user_id . "','19','" . $Religion . "', $sts_religion)";
                mysql_query($insert);
            }
        }
        
        $Martial = $_POST['Marital'];
        $hid_marital = $_POST['hid_marital'];
        $sts_marital = 1;
        if(isset($hid_marital)) $sts_marital = 0;
        if ($Martial != "") {
            $select_profiles = "select * from profile_field_values where user_id='" . $user_id . "' and profile_field_id='28'";
            $get_credits = mysql_query($select_profiles);
            $no_rows = mysql_num_rows($get_credits);
            if ($no_rows == 1) {
                $update = "update profile_field_values set value='" . $Martial . "', status=$sts_marital where profile_field_id='28' and user_id='" . $user_id . "' ";
                mysql_query($update);
            } else {
                $insert = "insert into profile_field_values(`user_id`,`profile_field_id`,`value`,`status`) value('" . $user_id . "','28','" . $Martial . "', $sts_marital)";
                mysql_query($insert);
            }
        }
        
        $Income = $_POST['Income'];
        $hid_income = $_POST['hid_income'];
        $sts_income = 1;
        if(isset($hid_income)) $sts_income = 0;
        if ($Income != "") {
            $select_profiles = "select * from profile_field_values where user_id='" . $user_id . "' and profile_field_id='27'";
            $get_credits = mysql_query($select_profiles);
            $no_rows = mysql_num_rows($get_credits);
            if ($no_rows == 1) {
                $update = "update profile_field_values set value='" . $Income . "', status=$sts_income where profile_field_id='27' and user_id='" . $user_id . "' ";
                mysql_query($update);
            } else {
                $insert = "insert into profile_field_values(`user_id`,`profile_field_id`,`value`,`status`) value('" . $user_id . "','27','" . $Income . "', $sts_income)";
                mysql_query($insert);
            }
        }
        
        $Education = $_POST['Education'];
        $hid_education = $_POST['hid_education'];
        $sts_education = 1;
        if(isset($hid_education)) $sts_education = 0;
        if ($Education != "") {
            $select_profiles = "select * from profile_field_values where user_id='" . $user_id . "' and profile_field_id='26'";
            $get_credits = mysql_query($select_profiles);
            $no_rows = mysql_num_rows($get_credits);
            if ($no_rows == 1) {
                $update = "update profile_field_values set value='" . $Education . "', status=$sts_education where profile_field_id='26' and user_id='" . $user_id . "' ";
                mysql_query($update);
            } else {
                $insert = "insert into profile_field_values(`user_id`,`profile_field_id`,`value`,`status`) value('" . $user_id . "','26','" . $Education . "', $sts_education)";
                mysql_query($insert);
            }
        }
        $Pet = $_POST['Pet'];
        $hid_pet = $_POST['hid_pet'];
        $sts_pet = 1;
        if(isset($hid_pet)) $sts_pet = 0;
        if ($Pet != "") {
            $select_profiles = "select * from profile_field_values where user_id='" . $user_id . "' and profile_field_id='24'";
            $get_credits = mysql_query($select_profiles);
            $no_rows = mysql_num_rows($get_credits);
            if ($no_rows == 1) {
                $update = "update profile_field_values set value='" . $Pet . "', status=$sts_pet where profile_field_id='24' and user_id='" . $user_id . "' ";
                mysql_query($update);
            } else {
                $insert = "insert into profile_field_values(`user_id`,`profile_field_id`,`value`,`status`) value('" . $user_id . "','24','" . $Pet . "', $sts_pet)";
                mysql_query($insert);
            }
        }
        $Parent = $_POST['Parent'];
        $hid_parent = $_POST['hid_parent'];
        $sts_parent = 1;
        if(isset($hid_parent)) $sts_parent = 0;
        if ($Parent != "") {
            $select_profiles = "select * from profile_field_values where user_id='" . $user_id . "' and profile_field_id='23'";
            $get_credits = mysql_query($select_profiles);
            $no_rows = mysql_num_rows($get_credits);
            if ($no_rows == 1) {
                $update = "update profile_field_values set value='" . $Parent . "', status=$sts_parent where profile_field_id='23' and user_id='" . $user_id . "' ";
                mysql_query($update);
            } else {
                $insert = "insert into profile_field_values(`user_id`,`profile_field_id`,`value`,`status`) value('" . $user_id . "','23','" . $Parent . "', $sts_parent)";
                mysql_query($insert);
            }
        }
        $Website = $_POST['Website'];
        $hid_website = $_POST['hid_website'];
        $sts_website = 1;
        if(isset($hid_website)) $sts_website = 0;
        if ($Website != "") {
            $select_profiles = "select * from profile_field_values where user_id='" . $user_id . "' and profile_field_id='32'";
            $get_credits = mysql_query($select_profiles);
            $no_rows = mysql_num_rows($get_credits);
            if ($no_rows == 1) {
                $update = "update profile_field_values set value='" . $Website . "', status=$sts_website where profile_field_id='32' and user_id='" . $user_id . "' ";
                mysql_query($update);
            } else {
                $insert = "insert into profile_field_values(`user_id`,`profile_field_id`,`value`,`status`) value('" . $user_id . "','32','" . $Website . "', $sts_website)";
                mysql_query($insert);
            }
        }

        $Occupation = $_POST['Occupation'];
        $hid_occupation = $_POST['hid_occupation'];
        $sts_occupation = 1;
        if(isset($hid_occupation)) $sts_occupation = 0;
        if ($Occupation != "") {
            $select_profiles = "select * from profile_field_values where user_id='" . $user_id . "' and profile_field_id='31'";
            $get_credits = mysql_query($select_profiles);
            $no_rows = mysql_num_rows($get_credits);
            if ($no_rows == 1) {
                $update = "update profile_field_values set value='" . $Occupation . "', status=$sts_occupation where profile_field_id='31' and user_id='" . $user_id . "' ";
                mysql_query($update);
            } else {
                $insert = "insert into profile_field_values(`user_id`,`profile_field_id`,`value`,`status`) value('" . $user_id . "','31','" . $Occupation . "', $sts_occupation)";
                mysql_query($insert);
            }
        }

        $Sexual = $_POST['Sexual'];
        $hid_sexual = $_POST['hid_sexual'];
        $sts_sexual = 1;
        if(isset($hid_sexual)) $sts_sexual = 0;
        if ($Sexual != "") {
            $select_profiles = "select * from profile_field_values where user_id='" . $user_id . "' and profile_field_id='29'";
            $get_credits = mysql_query($select_profiles);
            $no_rows = mysql_num_rows($get_credits);
            if ($no_rows == 1) {
                $update = "update profile_field_values set value='" . $Sexual . "', status=$sts_sexual where profile_field_id='29' and user_id='" . $user_id . "' ";
                mysql_query($update);
            } else {
                $insert = "insert into profile_field_values(`user_id`,`profile_field_id`,`value`,`status`) value('" . $user_id . "','29','" . $Sexual . "', $sts_sexual)";
                mysql_query($insert);
            }
        }
        
        if($_FILES['file_prof_pic']['error'] == "0"){
            $ext = pathinfo(WWW_ROOT . 'img/uploads/Moderators/' . $_FILES['file_prof_pic']['name']);

            if ($this->check_image_extension($ext['extension'])) {
                $image_name = uniqid('RTU', true) . '.' . $ext['extension'];
//              if (!file_exists(WWW_ROOT . 'img/uploads/Moderators/' . $image_name)) {
                    move_uploaded_file($_FILES['file_prof_pic']['tmp_name'], WWW_ROOT . 'img/uploads/Moderators/' . $image_name);

                    $update_prof = "update user_profiles set image='" . $image_name . "' where user_id='" . $user_id . "'";
                    mysql_query($update_prof);//return true
//            }
            }
        }

        $day = $_POST['day'];
        $month = $_POST['month'];
        $year = $_POST['year'];
        $dates =  $year ."-". $month . "-" . $day;
        $hid_dob = $_POST['hid_dob'];
        $sts_dob = 1;
        if(isset($hid_dob)) $sts_dob = 0;
        if ($day != "") {
            $select_profiles = "select * from profile_field_values where user_id='" . $user_id . "' and profile_field_id='34'";
            $get_credits = mysql_query($select_profiles);
            $no_rows = mysql_num_rows($get_credits);
            if ($no_rows == 1) {
                $update = "update profile_field_values set value='" . $dates . "', status=$sts_dob where profile_field_id='34' and user_id='" . $user_id . "' ";
                mysql_query($update);
            } else {
                $insert = "insert into profile_field_values(`user_id`,`profile_field_id`,`value`,`status`) value('" . $user_id . "','34','" . $dates . "', $sts_dob)";
                mysql_query($insert);
            }
        }
    }

    function _get_user_infor($user_id) {
        $get_credits = mysql_query("SELECT * FROM `user_profiles` WHERE user_id ='$user_id'");
        $users = array();

        while ($row = mysql_fetch_assoc($get_credits)) {
            $users['filename'] = $row['screenname'];
        }
        //$users['filename']=$row['screenname'];
        $select_profiles = "select * from profile_field_values where user_id='" . $user_id . "'";
        $get_credits = mysql_query($select_profiles);
        while ($row = mysql_fetch_assoc($get_credits)) {
            if ($row['profile_field_id'] == "13") {
                $users['firstname'] = $row['value'];
            };            

            if ($row['profile_field_id'] == "14") {
                $users['lastname'] = $row['value'];
            }

            if ($row['profile_field_id'] == "15") {
                $users['Gender'] = $row['value'];
                $users['sts_Gender'] = $row['status'];
            }
            
            if ($row['profile_field_id'] == "17") {
                $users['Address'] = $row['value'];
                $users['sts_Address'] = $row['status'];
            }

            if ($row['profile_field_id'] == "19") {
                $users['Religion'] = $row['value'];
                $users['sts_Religion'] = $row['status'];
            }

            if ($row['profile_field_id'] == "20") {
                $users['Country'] = $row['value'];
                $users['sts_Country'] = $row['status'];
            }

            if ($row['profile_field_id'] == "21") {
                $users['Race'] = $row['value'];
                $users['sts_Race'] = $row['status'];
            }

            if ($row['profile_field_id'] == "22") {
                $users['Age'] = $row['value'];
                $users['sts_Age'] = $row['status'];
            }
            
            if ($row['profile_field_id'] == "23") {
                $users['Parent'] = $row['value'];
                $users['sts_Parent'] = $row['status'];
            }

            if ($row['profile_field_id'] == "24") {
                $users['Pet'] = $row['value'];
                $users['sts_Pet'] = $row['status'];
            }

            if ($row['profile_field_id'] == "25") {
                $users['State'] = $row['value'];
                $users['sts_State'] = $row['status'];
            }

            if ($row['profile_field_id'] == "26") {
                $users['Education'] = $row['value'];
                $users['sts_Education'] = $row['status'];
            }

            if ($row['profile_field_id'] == "27") {
                $users['Income'] = $row['value'];
                $users['sts_Income'] = $row['status'];
            }

            if ($row['profile_field_id'] == "28") {
                $users['Marital'] = $row['value'];
                $users['sts_Marital'] = $row['status'];
            }

            if ($row['profile_field_id'] == "29") {
                $users['Sexual'] = $row['value'];
                $users['sts_Sexual'] = $row['status'];
            }

            if ($row['profile_field_id'] == "30") {
                $users['City'] = $row['value'];
                $users['sts_City'] = $row['status'];
            }
            
            if ($row['profile_field_id'] == "31") {
                $users['Occupation'] = $row['value'];
                $users['sts_Occupation'] = $row['status'];
            }
            
            if ($row['profile_field_id'] == "32") {
                $users['Website'] = $row['value'];
                $users['sts_Website'] = $row['status'];
            }
            
            if ($row['profile_field_id'] == "33") {
                $users['About'] = $row['value'];
                $users['sts_About'] = $row['status'];
            }
            
            if ($row['profile_field_id'] == "34") {
                $users['birthday'] = $row['value'];
                $users['sts_birthday'] = $row['status'];
                $arr_dob = explode('-', $users['birthday']);
                $users['year'] = isset($arr_dob[0])?$arr_dob[0]:"1900";
                $users['month'] = isset($arr_dob[1])?$arr_dob[1]:"1";
                $users['day'] = isset($arr_dob[2])?$arr_dob[2]:"1";
            }
        }
//     	$select_profilelast="select * from profile_field_values where user_id='".$user_id."' and profile_field_id='14'";
//		$get_credits_last = mysql_query($select_profilelast);
//		while ($rows = mysql_fetch_assoc($get_credits_last)) 
//		{
//				$users['lastname']=$rows['value'];			
//        }	

        $select_profiless = "select * from user where id='" . $user_id . "'";
        $get_credits = mysql_query($select_profiless);
        while ($row = mysql_fetch_assoc($get_credits)) {
            $users['email'] = $row['email'];
            $users['password'] = $row['password'];
            $users['username'] = $row['username'];
        }
        
        $select_profiles = "select * from user_profiles where user_id='" . $user_id . "'";
        $get_profiles = mysql_query($select_profiles);
        while ($row = mysql_fetch_assoc($get_profiles)) {
            $users['dob'] = $row['dob'];
//            $arr_dob = explode('-', $users['dob']);
//            $users['year'] = isset($arr_dob[0])?$arr_dob[0]:"1900";
//            $users['month'] = isset($arr_dob[1])?$arr_dob[1]:"1";
//            $users['day'] = isset($arr_dob[2])?$arr_dob[2]:"1";
        }

        return $users;
    }

    function _get_profile_field() {
        $subject_all = array();
        $get_credits = mysql_query("SELECT * FROM `profile_fields`");
        while ($row = mysql_fetch_assoc($get_credits)) {
            if ($row['title'] == "Gender") {
                $subject_all['Gender'] = $row['value'];
            }
            if ($row['title'] == "Country") {
                $subject_all['Country'] = $row['value'];
            }
            if ($row['title'] == "State") {
                $subject_all['State'] = $row['value'];
            }
            if ($row['title'] == "State") {
                $subject_all['State'] = $row['value'];
            }
            if ($row['title'] == "Religion") {
                $subject_all['Religion'] = $row['value'];
            }
            if ($row['title'] == "Marital status") {
                $subject_all['Marital'] = $row['value'];
            }
            if ($row['title'] == "Race") {
                $subject_all['Race'] = $row['value'];
            }
            if ($row['title'] == "Pet Owner") {
                $subject_all['Pet'] = $row['value'];
            }
            if ($row['title'] == "Are you a parent") {
                $subject_all['Parent'] = $row['value'];
            }
            if ($row['title'] == "Education") {
                $subject_all['Education'] = $row['value'];
            }
            if ($row['title'] == "Income") {
                $subject_all['Income'] = $row['value'];
            }
            if ($row['title'] == "Sexual Orientation") {
                $subject_all['Sexual'] = $row['value'];
            }
            if ($row['title'] == "City") {
                $subject_all['City'] = $row['value'];
            }
            if ($row['title'] == "Occupation") {
                $subject_all['Occupation'] = $row['value'];
            }
        }

        return $subject_all;
    }
    
    function _trans_user_info($user_id){
        $profile_fields = $this->_get_profile_field();
        
        $genders = explode(",", $profile_fields['Gender']);
        $countries = explode(",", $profile_fields['Country']);
        $states = explode(",", $profile_fields['State']);
        $city = explode(",", $profile_fields['City']);
        $races = explode(",", $profile_fields['Race']);
        $sexual = explode(",", $profile_fields['Sexual']);
        $religions = explode(",", $profile_fields['Religion']);
        $martials = explode(",", $profile_fields['Marital']);
        $incomes = explode(",", $profile_fields['Income']);
        $occupation = explode(",", $profile_fields['Occupation']);
        $educations = explode(",", $profile_fields['Education']);
        $pets = explode(",", $profile_fields['Pet']);
        $parents = explode(",", $profile_fields['Parent']);
        
        $user_info = $this->_get_user_infor($user_id);
        $user_info['Gender'] = $genders[$user_info['Gender']-1];
        $user_info['Country'] = $countries[$user_info['Country']-1];
        $user_info['State'] = $states[$user_info['State']-1];
        $user_info['City'] = $city[$user_info['City']-1];
        $user_info['Race'] = $races[$user_info['Race']-1];
        $user_info['Sexual'] = $sexual[$user_info['Sexual']-1];
        $user_info['Religion'] = $religions[$user_info['Religion']-1];
        $user_info['Marital'] = $martials[$user_info['Marital']-1];
        $user_info['Income'] = $incomes[$user_info['Income']-1];
        $user_info['Occupation'] = $occupation[$user_info['Occupation']-1];
        $user_info['Education'] = $educations[$user_info['Education']-1];
        $user_info['Pet'] = $pets[$user_info['Pet']-1];
        $user_info['Parent'] = $parents[$user_info['Parent']-1];
        
        return $user_info;
    }
    
    function _get_universal($user_id) {
        $universal = array();
        $select_profiles = "SELECT * FROM `suggested_adjectives` as a inner join subject as b on a.subject_id=b.id WHERE a.user_id ='" . $user_id . "'";
        $get_credits = mysql_query($select_profiles);
        while ($row = mysql_fetch_assoc($get_credits)) {
            $universal[] = $row['subject'];
        }
        return $universal;
    }

    function _get_tags() {
        $tags = $this->Tag->find('all', array('conditions' => array('Tag.type =' => 'tag'), 'group' => array('Tag.title'), 'fields' => array('Tag.id', 'Tag.title'), 'order' => 'title ASC'));
        return $tags;
    }

    //return the subject_rates of current user
    function _get_voting_history(){
        if (isset($_SESSION['Auth']['user']['User']['id']))
            $user_id = $_SESSION['Auth']['user']['User']['id'];
        else
            return "[]";
        
        $this->SubjectRate->recursive = -1;
        $conditions = array("SubjectRate.user_id" => $user_id);            
        $join_table = array(
                array('table' => 'subject',
                    'alias' => 'Subject',
                    'type' => 'INNER',
                    'conditions' => array(
                        'SubjectRate.subject_id = Subject.id',
                    )
                )
        );
        $rates = $this->SubjectRate->find('all', array(
            'fields' => array('SubjectRate.id','SubjectRate.subject_id','SubjectRate.rating','SubjectRate.user_id','Subject.subject'),
            'conditions' => $conditions,
            'joins' => $join_table,
            'recursive' => -1,
            'order' => 'Subject.subject ASC'
        ));
        for($i=0;$i<count($rates); $i++){
            $rates[$i]['Subject']['subject'] = htmlspecialchars($rates[$i]['Subject']['subject'], ENT_QUOTES);
        }
        return json_encode($rates);
    }
}

?>
